package net.sunofbeach.blog.services.impl;

import lombok.extern.slf4j.Slf4j;
import net.sunofbeach.blog.dao.DiaryDao;
import net.sunofbeach.blog.pojo.Diary;
import net.sunofbeach.blog.response.ResponseResult;
import net.sunofbeach.blog.services.IDiaryService;
import net.sunofbeach.blog.services.IUserService;
import net.sunofbeach.blog.utils.IdWorker;
import net.sunofbeach.blog.utils.TextUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.Date;

@Slf4j
@Service
@Transactional
public class DiaryServiceImpl extends BaseService implements IDiaryService {
    @Autowired
    private IUserService userService;

    @Autowired
    private IdWorker idWorker;

    @Autowired
    private DiaryDao diaryDao;

    @Override
    public ResponseResult postDiary(Diary diary) {
        //检查数据
        //检查用户，获取到用户对象
//        SobUser sobUser = userService.checkSobUser();
//
//        //未登录
//        if (sobUser == null) {
//            return ResponseResult.ACCOUNT_NOT_LOGIN();
//        }
        //内容
        int imageNum = diary.getImageNum();
        String content = diary.getContent();
        if (TextUtils.isEmpty(content)) {
            return ResponseResult.FAILED("内容不可以为空");
        }
        String cover1 = diary.getCover1();

        //这里改一下
//        if (TextUtils.isEmpty(cover1)) {
//            return ResponseResult.FAILED("请至少添加一张图片");
//        }

        if (!TextUtils.isEmpty(cover1)) {
            imageNum = imageNum+1;
        }


        String cover2 = diary.getCover2();
        if (!TextUtils.isEmpty(cover2)) {
            imageNum = imageNum+1;
        }
        String cover3 = diary.getCover3();
        if (!TextUtils.isEmpty(cover3)) {
            imageNum = imageNum+1;
        }



        //补全内容
        //1.头像（默认，或者多给几个随机）2.id 3.创建时间
        diary.setImageNum(imageNum);

        diary.setState("1");
        diary.setId(idWorker.nextId() + "");

        diary.setCreateTime(new Date());
        diaryDao.save(diary);
        return ResponseResult.SUCCESS("发布微博成功");
    }

    @Override
    public ResponseResult listDiary(int page, int size) {
        page = checkPage(page);
        size = checkSize(size);
        //没有就往下走
        Sort sort = new Sort(Sort.Direction.DESC, "createTime");
        Pageable pageable = PageRequest.of(page - 1, size, sort);
        Page<Diary> all =diaryDao.findAll(pageable);
        return ResponseResult.SUCCESS("获取微博列表成功").setData(all);
    }
}

